<?php
/**
 * Created by PhpStorm.
 * User: liuyu
 * Date: 2018/6/6
 * Time: 16:16
 */

namespace app\api\controller\v2;

use app\common\lib\astrolog\Astrolog;
use app\common\lib\exception\ApiException;
use app\common\model\Article;
use app\common\model\Button;
use app\common\cachemodel\FortuneCache;
use app\common\model\Slide;
use app\everyday\controller\Index as FortuneIndex;

/**
 * @title 首页接口
 * @desc 首页获取个人太阳星座周运和上升星座周运<br/>根据版本号获取首页按钮<br/>获取星文推荐的文章十条
 * @url /api/v2/index
 * @version 2.0.0
 * Class Index
 * @package app\api\controller\v2
 */
class Index extends Auth
{
    protected $restActionList = ['index'];

    /**
     * @title 首页接口
     * @method GET
     * @desc 无需另外传参
     * @readme /doc/api/index/index.md
     * @return array
     * @throws ApiException
     */
    public function index()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }

        $time_now = time();

        $map = ['uid' => $this->user['id'], 'isself' => 1];

        $recode_info = (new \app\common\model\Recode())->getSelfRecode($map);

        if (empty($recode_info))
        {
            return show(config('code.denied'), '当前账号登录过期，请您重新登录。', [], 200);
        }

        $recode_info['longitude'] = ($recode_info['long_deg'] + $recode_info['long_min'] / 60) * $recode_info['ew'];
        $recode_info['latitude'] = ($recode_info['lat_deg'] + $recode_info['lat_min'] / 60) * $recode_info['ns'];

        // 开始获取首页 日运主题 && 宜忌
        $dailyFortune = new FortuneIndex();

        //如果错误的话，也返回数据，否则首页就加载失败了
        $lucky_name = [];//宜
        $avoid = [];//忌
        $revive_day = ['name' => '', 'star_level' => 0, 'tips' => '', 'icon_url' => '', 'tips_url' => ''];//**之日
        $sun_in_sign = 1;//周运星座
        $tips = '';//今日天象

        $is_use_cache = 1;
        if ($is_use_cache)
        {//匹配返回的数据，放入缓存中
            $map = ['time' => $time_now, 'recode' => $recode_info];
            try
            {
                //$fortune_cache = (new \app\common\model\FortuneCache())->getHomePageFortune($map);
                $fortune_cache = (new FortuneCache())->getHomePageFortune($map);
                $lucky_name = $fortune_cache['lucky_name'];
                $avoid = $fortune_cache['forbid_name'];
                $revive_day = $fortune_cache['revive_day'];
                $sun_in_sign = $fortune_cache['sun_in_sign'];
                $tips = $fortune_cache['tips'];
            }
            catch (\Exception $e)
            {
                // 错误信息写入日志
                \think\Log::write('首页获取日运缓存数据错误:' . 'uid=[' . $this->user['id'] . ']'.$e->getMessage(), 'error', true);
            }


        } else
        {

            $dailyTime = strtotime(date('Y-m-d', $time_now) . ' 12:00:00');
            $timeinfo = [
                'year' => date('Y', $dailyTime),
                'month' => date('m', $dailyTime),
                'day' => date('d', $dailyTime),
                'hour' => date('H', $dailyTime),
                'minute' => date('i', $dailyTime),
            ];
            $timeinfo['timezone'] = 8;
            $timeinfo['is_summer'] = isSummerTime($timeinfo['hour'], $timeinfo['minute'], 0,
                $timeinfo['month'], $timeinfo['day'], $timeinfo['year']) ? 1 : 0;

            $dailyFortune->astro = Astrolog::getInstance();
            $dailyFortune->astro
                ->setRecode1($recode_info)
                ->setAdvance($timeinfo)
                ->setExecPrefix(config('astrolog.prefix'))
                ->setIsAstrolabe(false)
                ->setUserSetting(config('astroset.setting1'))
                ->setGetDatas(['now', 'natal', 'transits', 'thirdprogressed'])
                ->getAstroDatas();

            $dailyFortune->nowData = $dailyFortune->astro->getDatas('now');
            $dailyFortune->natalData = $dailyFortune->astro->getDatas('natal');
            $dailyFortune->transitsData = $dailyFortune->astro->getDatas('transits');
            $dailyFortune->thirdprogressedData = $dailyFortune->astro->getDatas('thirdprogressed');
            $dailyFortune->active = $dailyFortune->getActive();
            $lucky_name = $dailyFortune->getSuitable($recode_info, $dailyTime, true);
            $forbid_name = $dailyFortune->getAvoid(true);
            $avoid = [];
            // 宜中出现过的，忌中不显示
            if (!empty($forbid_name)) foreach ($forbid_name as $avd) if (!in_array($avd, $lucky_name)) $avoid[] = $avd;

            $revive_day = $dailyFortune->getTopic($recode_info, $dailyTime, true);

            $sun_in_sign = $dailyFortune->natalData['planets'][0]['in_sign_id'] ?? 1;// 如失败 则为白羊座
            // 获取今日天象
            $timeinfo['hour'] = 0;

            $dailyFortune->nowData = $dailyFortune->astro
                ->setAdvance($timeinfo)
                ->setGetDatas(['now'])
                ->getAstroDatas()
                ->getDatas('now');

            $tips = $dailyFortune->getNow();
        }

        $Article = new Article();

        $week = $Article->getFortune('week', $sun_in_sign);

        $sun_article = $week['content'];

        // 首页轮播
        $slide = (new Slide())->getSlideVersion();

        // 首页按钮
        $btns = (new Button())->getButton(['ver' => $this->headers['version']]);

        $map_article['a.cid'] = array(['<', 3], ['>', 42], 'or');
        $map_article['a.status'] = 1;// 已审核
        $map_article['a.is_recommend'] = 1;// 首页显示
        $map_article['uid'] = $this->user['id'];
        $map_article['uc_id'] = $this->user['uc_id'];

        // 获取首页文章
        $articles = $Article->getIndexArticle($map_article);


        $data = [
            'in_sign' => $sun_in_sign,
            'slides' => $slide,
            'buttons' => $btns,
            'today_fortune' => [
                'revive_day' => $revive_day,
                'lucky_name' => $lucky_name,
                'forbid_name' => $avoid,
            ],
            'content' => $sun_article,
            'today_astro' => [
                'time' => strtotime(date('Y-m-d', $time_now)),// 精确到天
                'tips' => $tips ?? '',
            ],
            'article' => $articles,
            'lucky_planet_switch' => true,// 幸运星功能开关
        ];
        return show(200, '首页加载成功', $data);
    }

    /**
     * 参数规则
     * @name 字段名称
     * @type 类型
     * @require 是否必须
     * @default 默认值
     * @desc 说明
     * @range 范围
     * @return array
     */
    public static function getRules()
    {
        $rules = [
            'index' => [

            ],
        ];
        return $rules;
    }
}
